﻿<%@ WebHandler Language="C#" Class="CommunityBuildingMgr" %>

using System;
using System.Web;
using System.Data;
using Chenxin.Lib.Utility;

/// <summary>
/// CommunityMgr Ajax服务页
/// 
/// 创建人：    熊世宏
/// 创建日期：  2010-04-12
/// </summary>
public class CommunityBuildingMgr : AjaxHandlerBase
{
    public CommunityBuildingMgr()
    {
        htTypePermit.Add("add", Constants.Permit_CommunityBuildingInfoAdd);
        htTypePermit.Add("del", Constants.Permit_CommunityBuildingInfoDel);
        htTypePermit.Add("edit", Constants.Permit_CommunityBuildingInfoEdit);
        htTypePermit.Add("bulkadd", Constants.Permit_CommunityBuildingInfoBulkAdd);
        htTypePermit.Add("logicdel", Constants.Permit_CommunityBuildingInfoLogicDel);
        htTypePermit.Add("lock", Constants.Permit_CommunityBuildingInfoLock);
        htTypePermit.Add("unlock", Constants.Permit_CommunityBuildingInfoUnLock);       
    }
    
    public override void RequestProcess(HttpContext context)
    {
        context.Response.AddHeader("pragma", "no-cache");
        context.Response.AddHeader("cache-control", "");
        context.Response.CacheControl = "no-cache";
        
        if (context.Request["op"] != null)
        {
            switch (context.Request["op"].ToLower())
            {
                case "add":
                    Add(context);
                    break;
                case "edit":
                    Edit(context);
                    break;
                case "del":
                    Del(context);
                    break;
                case "getlist":
                    GetList(context);
                    break;
                case "getmodel":
                    GetModel(context);
                    break;
                case "validate":
                    Validate(context);
                    break;
                case "getcombolist":
                    GetComboList(context);
                    break;      
                case "bulkadd":
                    BulkAdd(context);
                    break;
                case "logicdel":
                    LogicDel(context);
                    break;
                case "lock":
                    Lock(context);
                    break;
                case "unlock":
                    UnLock(context);
                    break;    
                case "getinfo":
                    GetInfo(context);
                    break;     
                default:
                    break;
            }
        }
    }

    /// <summary>
    /// 批量添加
    /// </summary>
    /// <param name="context"></param>
    private void BulkAdd(HttpContext context)
    {
        try
        {
            if (context.Request["model"] != null)
            {
                Chenxin.Lib.House.Entity.Community_BuildingInfo model = (Chenxin.Lib.House.Entity.Community_BuildingInfo)Chenxin.Lib.Utility.JsonHelp.Convert2Entity(context.Request["model"], typeof(Chenxin.Lib.House.Entity.Community_BuildingInfo));

                model.AddTime = DateTime.Now;
                model.AddPerson = CurrentUserInfo.UserName;
                model.Status = 1;

                int count = 0;
                string nameList = "";
                int maxNum = 0;
                int minNum = 0;
                int step = 1;
                if (context.Request["step"] != null)
                {
                    step = Convert.ToInt32(context.Request["step"]);
                }
                if (context.Request["setting"] == "number")
                {
                    maxNum = Convert.ToInt32(context.Request["MaxNumber"]) > Convert.ToInt32(context.Request["MinNumber"]) ? Convert.ToInt32(context.Request["MaxNumber"]) : Convert.ToInt32(context.Request["MinNumber"]);
                    minNum = Convert.ToInt32(context.Request["MaxNumber"]) < Convert.ToInt32(context.Request["MinNumber"]) ? Convert.ToInt32(context.Request["MaxNumber"]) : Convert.ToInt32(context.Request["MinNumber"]);

                    for (int i = minNum; i <= maxNum; i += step)
                    {
                        string format = "";
                        int length = Convert.ToInt32(context.Request["LengthNumber"]);
                        while (length > 0)
                        {
                            format += "0";
                            length--;                        
                        }

                        nameList += model.BuildingName.Replace("(*)", string.Format(string.Format("{{0:{0}}}", format), i) + context.Request["BuildingNameType"]) + ",";
                    }
                }
                else
                {
                    maxNum = Convert.ToInt32(context.Request["MaxChar"][0]) > Convert.ToInt32(context.Request["MinChar"][0]) ? Convert.ToInt32(context.Request["MaxChar"][0]) : Convert.ToInt32(context.Request["MinChar"][0]);
                    minNum = Convert.ToInt32(context.Request["MaxChar"][0]) < Convert.ToInt32(context.Request["MinChar"][0]) ? Convert.ToInt32(context.Request["MaxChar"][0]) : Convert.ToInt32(context.Request["MinChar"][0]);

                    for (int i = minNum; i <= maxNum; i += step)
                    {
                        nameList += model.BuildingName.Replace("(*)", (char)i + context.Request["BuildingNameType"])+",";
                    }
                }

                string[] nameArray = GetInsertBuildingName(model.CommunityId, nameList).Split(',');
                string nameTemp="";
                foreach (string name in nameArray)
                {
                    if (name != "")
                    {
                        model.BuildingId = System.Guid.NewGuid();
                        model.BuildingName = name;
                        nameTemp += name + ',';
                        Chenxin.Lib.House.DAL.Community_BuildingInfo.Add(model);
                        count++;
                    }
                }

                
                if (count > 0)
                {
                    if (count == nameList.Split(',').Length-1)
                    {
                        context.Response.Write("{success:'1',msg:'全部批量添加成功！',data:''}");
                    }
                    else
                    {
                        context.Response.Write("{success:'1',msg:'部分添加成功！" + nameTemp + "',data:''}");
                    }

                    //删除第一页楼栋缓存
                    string strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_COMMUNITY_BUILDINGS, model.CommunityId.ToString().ToLower() + "_1");
                    Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
                    //cs.Delete(strCachKey);
                    cs.Delete(strCachKey + "_4");
                    cs.Delete(strCachKey + "_100");
                    cs.Delete(strCachKey + "_50");


                    //删除下拉框缓存
                    strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_COMMUNITY_BUILDINGS, model.CommunityId.ToString().ToLower());
                    cs.Delete(strCachKey);
                    
                    
                    //添加用户操作日志 2010-5-12 王玮 Add
                    AddLog("" + CurrentUserInfo.UserName + "批量添加了一些楼栋",
                            OperationType.OperationTypeComboList()["OprType_CommunityBuildingAdd"].ToString());
                }
                else
                {
                    context.Response.Write("{success:'0',msg:'批量添加失败！所需要添加的楼栋已经存在',data:''}");
                }

            }
        }
        catch(Exception e)
        {
            context.Response.Write("{success:'0',msg:'批量添加失败！原因："+e.Message+"',data:''}");            
        }
    }

    /// <summary>
    /// 获取需要插入的名称字符串，用于批量添加，排除已经插入过的楼栋
    /// </summary>
    /// <param name="communityId"></param>
    /// <param name="nameList"></param>
    /// <returns></returns>
    private string GetInsertBuildingName(Guid communityId, string nameList)
    {
        DataTable dt = Chenxin.Lib.House.DAL.Community_BuildingInfo.GetList(string.Format(" CommunityId='{0}' and Status<>-1", communityId), "BuildingName");

        string tempList = "," + nameList;
        foreach (DataRow dr in dt.Rows)
        {
            tempList = tempList.Replace("," + dr.ItemArray[0].ToString() + ",", ",");

        }
        return tempList;
    }
    
    /// <summary>
    /// 获取指定小区的楼栋Combo
    /// </summary>
    /// <param name="context"></param>
    private void GetComboList(HttpContext context)
    {
        if (context.Request["communityid"] != null)
        {
            DataSet ds = null;

            string strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_COMMUNITY_BUILDINGS, context.Request["communityid"].ToLower());
            Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
            ds = cs.GetObject<DataSet>(strCachKey);
            if (!cs.Hit)
            {
                ds = Chenxin.Lib.House.DAL.Community_BuildingInfo.GetList(string.Format(" CommunityId='{0}' and Status=1", context.Request["communityid"]));
                if (ds != null)
                {
                    cs.Set(strCachKey, ds, DateTime.Now.AddDays(1));
                }
            }

            System.Text.StringBuilder itemsSb = new System.Text.StringBuilder();
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                itemsSb.AppendFormat("{{txt:'{0}',val:'{1}'}},", dr["BuildingName"], dr["BuildingId"]);
            }

            context.Response.Write(string.Format("{{success:'1',msg:'',data:{{items:[{0}]}}}}", itemsSb.Length > 0 ? itemsSb.Remove(itemsSb.Length - 1, 1).ToString() : itemsSb.ToString()));
        }
        else
        {
            context.Response.Write("{success:'0',msg:'',data:''}");
        }
    }

    /// <summary>
    /// 验证
    /// </summary>
    /// <param name="context"></param>
    private void Validate(HttpContext context)
    {
        string strWhere = "";//为空是执行判断列存在，否则执行查询条件判断存在
        bool exist = false;
        
        if (context.Request["clientid"] != null && context.Request[context.Request["clientid"]] != null)
        {
            string columnName = "";
            switch (context.Request["clientid"])
            {
                case "txtBuildingName":
                    columnName = "BuildingName";
                    strWhere = string.Format(" (BuildingName='{0}号' or BuildingName='{0}幢' or BuildingName='{0}栋' or BuildingName='{0}座' or BuildingName='{0}') and CommunityId='{1}' and Status<>-1", context.Request["txtBuildingName"], context.Request["communityid"]);
                    break;
            }
            if (strWhere == "")
            {
                strWhere = string.Format(" {0}='{1}' and Status=1", columnName, context.Request[context.Request["clientid"]]);
                exist = Chenxin.Lib.House.DAL.Community_BuildingInfo.Exists(strWhere);
            }
            else
            {
                exist = Chenxin.Lib.House.DAL.Community_BuildingInfo.Exists(strWhere);
            }

            if (exist)
            {
                context.Response.Write("{success:'1',msg:'楼栋名称已经存在',data:''}");
            }
            else
            {
                context.Response.Write("{success:'1',msg:'',data:''}");
            }
        }
        else
        {
            context.Response.Write("{success:'0',msg:'',data:''}");
        }
    }

    /// <summary>
    /// 冻结
    /// </summary>
    /// <param name="context"></param>
    private void Lock(HttpContext context)
    {
        ChangeStatus(context, -10);
    }

    /// <summary>
    /// 解冻
    /// </summary>
    /// <param name="context"></param>
    private void UnLock(HttpContext context)
    {
        ChangeStatus(context, 1);
    }

    /// <summary>
    /// 逻辑删除
    /// </summary>
    /// <param name="context"></param>
    private void LogicDel(HttpContext context)
    {
        ChangeStatus(context, -1);
    }
    

    /// <summary>
    /// 逻辑删除
    /// </summary>
    /// <param name="context"></param>
    private void ChangeStatus(HttpContext context,int status)
    {
        string msg = "逻辑删除";
        if (status == 1)
        {
            msg = "激活";
        }
        else if (status == -10)
        {
            msg = "冻结";
        }
        try
        {
            if (context.Request["modelid"] != null && context.Request["checkhouse"] != null)
            {
                if (context.Request["checkhouse"] == "true")
                {
                    if (Chenxin.Lib.House.DAL.House_BaseInfo.Exists(string.Format("BuildingId='{0}'", context.Request["modelid"])))
                    {
                        context.Response.Write("{success:'1',msg:'" + msg + "失败！',data:{hasHouse:true}}");
                    }
                    else
                    {
                        Chenxin.Lib.House.DAL.Community_BuildingInfo.UpdateStatus(new Guid(context.Request["modelid"]), status);

                        Chenxin.Lib.House.Entity.Community_BuildingInfo model = Chenxin.Lib.House.DAL.Community_BuildingInfo.GetModel(new Guid(context.Request["modelid"]));

                        //删除第一页楼栋缓存
                        string strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_COMMUNITY_BUILDINGS, model.CommunityId.ToString().ToLower() + "_1");
                        Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
                        cs.Delete(strCachKey);
                        cs.Delete(strCachKey + "_4");
                        cs.Delete(strCachKey + "_100");
                        cs.Delete(strCachKey + "_50");
                        //删除下拉框缓存
                        strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_COMMUNITY_BUILDINGS, model.CommunityId.ToString().ToLower());
                        cs.Delete(strCachKey);


                        //删除Model缓存
                        strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.HOUSE_COMMUNITYBUILDINGINFO, context.Request["modelid"]);
                        cs.Delete(strCachKey);


                        //操作日志
                        AddLog(string.Format("{0}，工号：{1}，在{2}对楼栋{3}进行了{4}操作", CurrentUserInfo.UserName, CurrentUserInfo.UserCode, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), context.Request["modelid"], msg), "楼栋" + msg);
                        
                        context.Response.Write("{success:'1',msg:'" + msg + "成功！',data:''}");
                    }
                }
                else
                {
                    Chenxin.Lib.House.DAL.Community_BuildingInfo.UpdateStatus(new Guid(context.Request["modelid"]), status);


                    Chenxin.Lib.House.Entity.Community_BuildingInfo model = Chenxin.Lib.House.DAL.Community_BuildingInfo.GetModel(new Guid(context.Request["modelid"]));

                    //删除第一页楼栋缓存
                    string strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_COMMUNITY_BUILDINGS, model.CommunityId.ToString().ToLower() + "_1");
                    Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
                    cs.Delete(strCachKey);
                    cs.Delete(strCachKey + "_4");
                    cs.Delete(strCachKey + "_100");
                    cs.Delete(strCachKey + "_50");

                    //删除下拉框缓存
                    strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_COMMUNITY_BUILDINGS, model.CommunityId.ToString().ToLower());
                    cs.Delete(strCachKey);

                    //删除Model缓存
                    strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.HOUSE_COMMUNITYBUILDINGINFO, context.Request["modelid"]);
                    cs.Delete(strCachKey);



                    //操作日志
                    AddLog(string.Format("{0}，工号：{1}，在{2}对楼栋{3}进行了{4}操作", CurrentUserInfo.UserName, CurrentUserInfo.UserCode, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), context.Request["modelid"], msg), "楼栋" + msg);
                    
                    context.Response.Write("{success:'1',msg:'" + msg + "成功！',data:''}");
                }
            }
            else
            {
                context.Response.Write("{success:'0',msg:'" + msg + "失败,请选择一条记录！',data:''}");
            }
        }
        catch
        {
            context.Response.Write("{success:'0',msg:'" + msg + "失败！',data:''}");
        }
    }
    
    /// <summary>
    /// 删除楼栋
    /// </summary>
    /// <param name="context"></param>
    private void Del(HttpContext context)
    {
        try
        {
            if (context.Request["modelid"] != null)
            {
                if (!Chenxin.Lib.House.DAL.House_BaseInfo.Exists(string.Format(" BuildingId='{0}' and Status>-10", context.Request["modelid"])))//判断是否添加过房源，已经逻辑删除的视作删除
                {
                    Chenxin.Lib.House.Entity.Community_BuildingInfo clhecbi = Chenxin.Lib.House.DAL.Community_BuildingInfo.GetModel(new Guid(context.Request["modelid"]));

                    Chenxin.Lib.House.DAL.Community_BuildingInfo.Delete(new Guid(context.Request["modelid"]));


                    //删除第一页楼栋缓存
                    string strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_COMMUNITY_BUILDINGS, clhecbi.CommunityId.ToString().ToLower() + "_1");
                    Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
                    cs.Delete(strCachKey);
                    cs.Delete(strCachKey + "_4");
                    cs.Delete(strCachKey + "_100");



                    //删除下拉框缓存
                    strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_COMMUNITY_BUILDINGS, clhecbi.CommunityId.ToString().ToLower());
                    cs.Delete(strCachKey);


                    //添加用户操作日志 2010-5-12 王玮 Add
                    AddLog("" + CurrentUserInfo.UserName + "删除了一个楼栋:楼栋名称[" + clhecbi.BuildingName + "]",
                            OperationType.OperationTypeComboList()["OprType_CommunityBuildingDel"].ToString());

                    context.Response.Write("{success:'1',msg:'删除成功！',data:''}");
                }
                else
                {
                    context.Response.Write("{success:'0',msg:'该楼栋已经添加过房源记录，建议执行逻辑删除！',data:''}");
                }
            }
            else
            {
                context.Response.Write("{success:'0',msg:'删除失败,请选择一条记录！',data:''}");
            }
        }
        catch(Exception ex)
        {
            context.Response.Write(string.Format("{{success:'0',msg:'删除失败！{0}',data:''}}", ex.Message));
        }
    }

    /// <summary>
    /// 添加
    /// </summary>
    /// <param name="contentx"></param>
    public void Add(HttpContext context)
    {
        try
        {
            Chenxin.Lib.House.Entity.Community_BuildingInfo model = (Chenxin.Lib.House.Entity.Community_BuildingInfo)Chenxin.Lib.Utility.JsonHelp.Convert2Entity(context.Request["model"], typeof(Chenxin.Lib.House.Entity.Community_BuildingInfo));


            if (!CheckExist(model.BuildingName, model.CommunityId.ToString()))
            {
                model.AddTime = DateTime.Now;
                model.AddPerson = CurrentUserInfo.UserName;
                model.BuildingId = System.Guid.NewGuid();
                model.Status = 1;
                Chenxin.Lib.House.DAL.Community_BuildingInfo.Add(model);


                //删除第一页楼栋缓存
                string strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_COMMUNITY_BUILDINGS, model.CommunityId.ToString().ToLower() + "_1");
                Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
                cs.Delete(strCachKey);
                cs.Delete(strCachKey + "_4");
                cs.Delete(strCachKey + "_100");
                cs.Delete(strCachKey + "_50");
                //删除下拉框缓存
                strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_COMMUNITY_BUILDINGS, model.CommunityId.ToString().ToLower());
                cs.Delete(strCachKey);


                //添加用户操作日志 2010-5-12 王玮 Add
                AddLog("" + CurrentUserInfo.UserName + "添加了一个楼栋:楼栋名称[" + model.BuildingName + "]",
                        OperationType.OperationTypeComboList()["OprType_CommunityBuildingAdd"].ToString());

                context.Response.Write(("{success:'1',msg:'保存成功！',data:{BuildingId:'" + model.BuildingId + "'}}"));

            }
            else
            {
                context.Response.Write(("{success:'0',msg:'保存失败，该小区已经存在该楼栋！',data:''}"));     
            }
        }
        catch
        {
            context.Response.Write(("{success:'0',msg:'保存失败！',data:''}"));
        }

    }

    /// <summary>
    /// 检查是否在指定小区已经存在相同名称的楼盘
    /// </summary>
    /// <param name="buildingName"></param>
    /// <param name="communityId"></param>
    /// <returns></returns>
    private bool CheckExist(string buildingName,string communityId)
    {

        string strWhere = string.Format(" (BuildingName='{0}号' or BuildingName='{0}幢' or BuildingName='{0}座' or BuildingName='{0}栋' or BuildingName='{0}') and CommunityId='{1}' and Status<>-1", buildingName, communityId);
        return Chenxin.Lib.House.DAL.Community_BuildingInfo.Exists(strWhere);
        
    }
    

    /// <summary>
    /// 编辑
    /// </summary>
    /// <param name="context"></param>
    public void Edit(HttpContext context)
    {
        try
        {
            Chenxin.Lib.House.Entity.Community_BuildingInfo model = (Chenxin.Lib.House.Entity.Community_BuildingInfo)JsonHelp.Convert2Entity(context.Request["model"], typeof(Chenxin.Lib.House.Entity.Community_BuildingInfo));

            model.AddTime = DateTime.Now;
            model.AddPerson = CurrentUserInfo.UserName;
            // model.Status = 1;
            Chenxin.Lib.House.Entity.Community_BuildingInfo tempModel = Chenxin.Lib.House.DAL.Community_BuildingInfo.GetModel(model.BuildingId);
            Chenxin.Lib.House.Entity.Community_BaseInfo tempModel1 = Chenxin.Lib.House.DAL.Community_BaseInfo.GetModel(model.CommunityId);
            string strContext = string.Empty;
            strContext = "原小区名称：" + tempModel1.CommunityName + "；";
            if (tempModel.BuildingName != model.BuildingName)
            {
                strContext += "楼栋名称由[" + tempModel.BuildingName + "]改为：" + model.BuildingName + "；";
            }
            if (tempModel.Floor != model.Floor)
            {
                strContext += "总层数由[" + tempModel.Floor + "]改为：" + model.Floor + "；";
            }
            if (tempModel.UnitNum != model.UnitNum)
            {
                strContext += "单元数由[" + tempModel.UnitNum + "]改为：" + model.UnitNum + "；";
            }
            if (tempModel.UnitType != model.UnitType)
            {
                strContext += "单元类型由[" + tempModel.UnitType + "]改为：" + model.UnitType + "；";
            }
            if (tempModel.RoomRuleRemark != model.RoomRuleRemark)
            {
                strContext += "楼栋规则由[" + tempModel.RoomRuleRemark + "]改为：" + model.RoomRuleRemark + "；";
            }

            Chenxin.Lib.House.Entity.House_CommunityLogs hsComLogs = new Chenxin.Lib.House.Entity.House_CommunityLogs();
            hsComLogs.RecordId = Guid.NewGuid();
            hsComLogs.CityId = CurrentUserInfo.CityId;
            hsComLogs.CityName = CurrentUserInfo.CityName;
            hsComLogs.CompanyId = CurrentUserInfo.CompanyId;
            hsComLogs.CompanyName = CurrentUserInfo.CompanyName;
            hsComLogs.DepartId = CurrentUserInfo.DepartId;
            hsComLogs.DepartName = CurrentUserInfo.DepartName;
            hsComLogs.UserId = CurrentUserInfo.UserId;
            hsComLogs.UserName = CurrentUserInfo.UserName;
            hsComLogs.Addtime = DateTime.Now;
            hsComLogs.OprType = "小区楼栋";
            hsComLogs.OperationContext = strContext;
            
            Chenxin.Lib.House.DAL.Community_BuildingInfo.Update(model);
            Chenxin.Lib.House.DAL.House_CommunityLogs.Add(hsComLogs);

            string strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.HOUSE_COMMUNITYBUILDINGINFO, model.BuildingId);
            Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.HOUSE);
            cs.Set(strCachKey, model, DateTime.Now.AddDays(1));

            //删除第一页楼栋缓存
            strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_COMMUNITY_BUILDINGS, model.CommunityId.ToString().ToLower() + "_1");
            Chenxin.Lib.Cache.CacheService cs1 = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
            cs1.Delete(strCachKey + "_4");
            cs1.Delete(strCachKey + "_100");



            //删除下拉框缓存
            strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_COMMUNITY_BUILDINGS, model.CommunityId.ToString().ToLower());
            cs1.Delete(strCachKey);

            //添加用户操作日志 2010-5-12 王玮 Add
            AddLog("" + CurrentUserInfo.UserName + "编辑了一个楼栋:楼栋名称[" + model.BuildingName + "]",
                    OperationType.OperationTypeComboList()["OprType_CommunityBuildingEdit"].ToString());

            context.Response.Write(("{success:'1',msg:'保存成功！',data:{BuildingId:'" + model.BuildingId + "'}}"));
        }
        catch
        {
            context.Response.Write(("{success:'0',msg:'保存失败！',data:''}"));
        }
    }

    /// <summary>
    /// 获取Model
    /// </summary>
    /// <param name="context"></param>
    public void GetModel(HttpContext context)
    {
        try
        {
                Chenxin.Lib.House.Entity.Community_BuildingInfo model = null;

                string strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.HOUSE_COMMUNITYBUILDINGINFO, context.Request["modelid"]);
                Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.HOUSE);
                model = cs.GetObject<Chenxin.Lib.House.Entity.Community_BuildingInfo>(strCachKey);
                if (!cs.Hit)
                {
                    model = Chenxin.Lib.House.DAL.Community_BuildingInfo.GetModel(new Guid(context.Request["modelid"]));
                    if (model != null)
                    {
                        cs.Set(strCachKey, model, DateTime.Now.AddDays(1));
                    }
                }

                if (model != null)
                {
                    if (model.Status == 1)
                    {
                        context.Response.Write(("{success:'1',msg:'',data:{model:" + JsonHelp.Convert2Json(model) + "}}"));
                    }
                    else
                    {
                        context.Response.Write("{success:'0',msg:'获取记录失败，该楼栋已经被删除！',data:''}");
                    }
                }
                else
                {
                    context.Response.Write("{success:'0',msg:'小区信息不存在，获取记录信息失败！',data:''}");
                }
        }
        catch(Exception wrong)
        {
            context.Response.Write(("{success:'0',msg:'获取记录信息失败"+wrong.Message+"！',data:{model:{}}}"));
        }
    }

    public void GetInfo(HttpContext context)
    {
        try
        {
            Chenxin.Lib.House.Entity.Community_BuildingInfo model = null;

            string strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.HOUSE_COMMUNITYBUILDINGINFO, context.Request["modelid"]);
            Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.HOUSE);
            model = cs.GetObject<Chenxin.Lib.House.Entity.Community_BuildingInfo>(strCachKey);
            if (!cs.Hit)
            {
                model = Chenxin.Lib.House.DAL.Community_BuildingInfo.GetModel(new Guid(context.Request["modelid"]));
                if (model != null)
                {
                    cs.Set(strCachKey, model, DateTime.Now.AddDays(1));
                }
            }

            if (model != null)
            {
                if (model.Status == 1)
                {
                    if (model.RoomRule == "*")
                    {

                        string where = string.Format(" CommunityId='{0}' and BuildingId='{1}' and CompanyId='{2}' AND Status >-10 ", model.CommunityId, model.BuildingId, CurrentUserInfo.CompanyId);

                        Chenxin.Lib.House.Entity.House_BaseInfo modelHouse = Chenxin.Lib.House.DAL.House_BaseInfo.GetModel(where);

                        if (modelHouse != null)
                        {
                            context.Response.Write(("{success:'1',msg:'',data:{model:" + JsonHelp.Convert2Json(model) + ",exist:true,housemodel:" + JsonHelp.Convert2Json(modelHouse) + "}}"));
                        }
                        else
                        {
                            context.Response.Write(("{success:'1',msg:'',data:{model:" + JsonHelp.Convert2Json(model) + ",exist:false}}"));
                        }
                    }
                    else
                    {
                        context.Response.Write(("{success:'1',msg:'',data:{model:" + JsonHelp.Convert2Json(model) + "}}"));
                    }
                }
                else
                {
                    context.Response.Write("{success:'0',msg:'获取记录失败，该楼栋已经被删除！',data:''}");
                }
            }
            else
            {
                context.Response.Write("{success:'0',msg:'小区信息不存在，获取记录信息失败！',data:''}");
            }
        }
        catch (Exception wrong)
        {
            context.Response.Write(("{success:'0',msg:'获取记录信息失败" + wrong.Message + "！',data:{model:{}}}"));
        }        
    }

    /// <summary>
    /// 获取列表
    /// </summary>
    /// <param name="context"></param>
    public void GetList(HttpContext context)
    {
        string strWhere = "1=1";// = "Status=1";
        string order = "Community_BuildingInfo.BuildingName ";

        int pageSize = 10;
        int pageIndex = 1;
        int count = 0;

        if (context.Request["pagesize"] != null)
        {
            pageSize = Convert.ToInt32(context.Request["pagesize"]);
        }
        if (context.Request["pageindex"] != null)
        {
            pageIndex = Convert.ToInt32(context.Request["pageindex"]) + 1;
        }

        if (context.Request["communityid"] != null)
        {
            strWhere += string.Format(" and communityid='{0}'", context.Request["communityid"]);
        }

        if (context.Request["orderfield"] != null)
        {
            order = context.Request["orderfield"];
        }


        DataSet ds = null;

        if (context.Request["communityid"] != null && pageIndex == 1)
        {
            string strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_COMMUNITY_BUILDINGS, context.Request["communityid"].ToLower() + "_1_"+pageSize);
            Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
            ds = cs.GetObject<DataSet>(strCachKey);
            if (!cs.Hit)
            {
                ds = Chenxin.Lib.House.DAL.Community_BaseInfo.GetList(pageIndex, pageSize, order, "Community_BuildingInfo", strWhere, "*", "*", true);
                if (ds != null && ds.Tables[0].Rows.Count != 0)
                {
                    cs.Set(strCachKey, ds, DateTime.Now.AddDays(1));
                }
            }
        }
        else
        {
            ds = Chenxin.Lib.House.DAL.Community_BaseInfo.GetList(pageIndex, pageSize, order, "Community_BuildingInfo", strWhere, "*", "*", true);
        }
        count = Convert.ToInt32(ds.Tables[1].Rows[0].ItemArray[0]);

        context.Response.Write(string.Format("{{success:'1',data:{{data:'{0}',count:{1}}}}}", CreateGrid(ds.Tables[0].Select("1=1")), count));
        
    }

    /// <summary>
    /// 生成列表
    /// </summary>
    /// <param name="drList"></param>
    /// <returns></returns>
    public string CreateGrid(DataRow[] drList)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        sb.Append("<table style=\"width:100%; height:100%\" cellspacing=\"1\" class=\"tabsorternew\" id=\"report\">");
        sb.Append("<thead>");
        sb.Append("<tr><th>楼栋名称</th>");
        sb.Append("<th width=\"50\">层数</th>");
        sb.Append("<th width=\"80\" >创建人</th>");
        sb.Append("<th width=\"140\">创建时间</th>");
        sb.Append("<th width=\"40\">状态</th>");
        sb.Append("<th width=\"180\">操作</th>");
        sb.Append("</tr></thead>");
        sb.Append("<tbody>");

        foreach (DataRow dr in drList)
        {
            sb.AppendFormat("<tr id=\"{0}\">", dr["BuildingId"]);
            sb.AppendFormat("<td>{0}</td>", dr["BuildingName"]);
            sb.AppendFormat("<td>{0}</td>", dr["Floor"]);
            sb.AppendFormat("<td>{0}</td>", dr["AddPerson"]);
            sb.AppendFormat("<td>{0}</td>", Convert.ToDateTime(dr["AddTime"]).ToString("yyyy-MM-dd HH:mm:ss"));

            if (dr["Status"].ToString() == "-1")
            {
                sb.Append("<td><span style=\"color:#ff0000;\">已删除</span></td>");
            }
            else if (dr["Status"].ToString() == "-10")
            {
                sb.Append("<td><span style=\"color:#0000ff;\">已冻结</span></td>");  
            }
            else
            {
                sb.Append("<td><span style=\"color:#009900;\">正常</span></td>");              
            }

            System.Text.StringBuilder opsb = new System.Text.StringBuilder();
            opsb.AppendFormat("<a name=\"{0}\" class=\"a-communitybuilding-edit\" href=\"#\">编辑</a>", dr["BuildingId"]);
            opsb.AppendFormat(" | <a name=\"{0}\" class=\"a-communitybuilding-del\" href=\"#\">删除</a>", dr["BuildingId"]);
            opsb.AppendFormat(" | <a name=\"{0}\" class=\"a-communitybuilding-lock\" href=\"#\">冻结</a>", dr["BuildingId"]);
            opsb.AppendFormat(" | <a name=\"{0}\" class=\"a-communitybuilding-unlock\" href=\"#\">激活</a>", dr["BuildingId"]);
            opsb.AppendFormat(" | <a name=\"{0}\" class=\"a-communitybuilding-logicdel\" href=\"#\">逻辑删除</a>", dr["BuildingId"]);
            sb.AppendFormat("<td>{0}</td>", opsb.ToString());
            sb.Append("</tr>");
        }
        sb.Append("</tbody>");
        sb.Append("</table>");

        return sb.ToString();
    }
}